/**
 * 日程管理模块
 * 包含日程的增删改查、优先级排序等功能
 */

import scheduleReminder from '@/utils/scheduleReminder.js'

// 优先级排序算法
const calculatePriority = (schedule) => {
	let score = 0
	
	// 紧急程度（权重 40%）
	const urgencyScores = {
		'urgent': 4,
		'high': 3,
		'medium': 2,
		'low': 1
	}
	score += (urgencyScores[schedule.priority] || 1) * 0.4
	
	// 时间紧迫性（权重 40%）
	// 任务类型使用较低的时间得分，但仍可以通过优先级排序
	if (schedule.type === 'task') {
		// 任务类型根据优先级给予固定分数
		const taskTimeScores = {
			'urgent': 2,
			'high': 1.5,
			'medium': 1,
			'low': 0.5
		}
		score += (taskTimeScores[schedule.priority] || 1) * 0.4
	} else {
		// 日程类型使用原有的时间紧迫性计算
		const now = new Date()
		const deadline = new Date(schedule.endTime)
		const diffDays = Math.ceil((deadline - now) / (1000 * 60 * 60 * 24))
		
		let timeScore = 0
		if (diffDays < 0) timeScore = 4 // 已过期
		else if (diffDays === 0) timeScore = 3 // 今天截止
		else if (diffDays <= 3) timeScore = 2 // 3天内截止
		else if (diffDays <= 7) timeScore = 1 // 一周内截止
		else timeScore = 0 // 一周后截止
		
		score += timeScore * 0.4
	}
	
	// 完成状态（权重 20%）
	score += schedule.completed ? 0 : 2 * 0.2
	
	return score
}

export const scheduleModule = {
	namespaced: true,
	state: {
		schedules: [],
		hiddenCompletedSchedules: [], // 隐藏的已完成事项ID列表
		filters: {
			dateRange: 'all', // all, today, tomorrow, week, month, custom
			priority: 'all', // all, urgent, high, medium, low
			type: 'all', // all, schedule, task
			tags: [],
			completed: 'all' // all, completed, uncompleted
		},
		searchKeyword: ''
	},
	
	getters: {
		// 获取排序后的日程列表
		sortedSchedules: (state) => {
			return [...state.schedules]
				.map(schedule => ({
					...schedule,
					priorityScore: calculatePriority(schedule)
				}))
				.sort((a, b) => {
					// 首先按优先级分数排序（分数高的在前）
					if (a.priorityScore !== b.priorityScore) {
						return b.priorityScore - a.priorityScore
					}
					
					// 同一优先级下，按时间先后排序
					// 对于任务类型，使用创建时间或更新时间排序
					if (a.type === 'task' && b.type === 'task') {
						const timeA = new Date(a.updatedAt || a.createdAt || 0)
						const timeB = new Date(b.updatedAt || b.createdAt || 0)
						return timeA - timeB // 创建时间早的在前
					}
					
					// 对于日程类型，使用结束时间排序
					if (a.type !== 'task' && b.type !== 'task') {
						const endTimeA = new Date(a.endTime || 0)
						const endTimeB = new Date(b.endTime || 0)
						return endTimeA - endTimeB // 结束时间早的在前（时间越紧的在前）
					}
					
					// 混合类型时，日程类型优先于任务类型
					if (a.type !== 'task' && b.type === 'task') {
						return -1
					}
					if (a.type === 'task' && b.type !== 'task') {
						return 1
					}
					
					return 0
				})
		},
		
		// 获取过滤后的日程列表
		filteredSchedules: (state, getters) => {
			let schedules = getters.sortedSchedules
			
			// 按日期范围过滤（任务类型不按日期过滤）
			if (state.filters.dateRange !== 'all') {
				const now = new Date()
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
				
				schedules = schedules.filter(schedule => {
					// 任务类型不按日期过滤
					if ((schedule.type || 'schedule') === 'task') {
						return true
					}
					
					const scheduleDate = new Date(schedule.endTime)
					const scheduleDateOnly = new Date(scheduleDate.getFullYear(), scheduleDate.getMonth(), scheduleDate.getDate())
					
					switch (state.filters.dateRange) {
						case 'today':
							return scheduleDateOnly.getTime() === today.getTime()
						case 'tomorrow':
							const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
							return scheduleDateOnly.getTime() === tomorrow.getTime()
						case 'week':
							const weekLater = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
							return scheduleDateOnly >= today && scheduleDateOnly <= weekLater
						case 'month':
							const monthLater = new Date(today.getFullYear(), today.getMonth() + 1, today.getDate())
							return scheduleDateOnly >= today && scheduleDateOnly <= monthLater
						default:
							return true
					}
				})
			}
			
			// 按优先级过滤
			if (state.filters.priority !== 'all') {
				schedules = schedules.filter(schedule => schedule.priority === state.filters.priority)
			}
			
			// 按类型过滤
			if (state.filters.type !== 'all') {
				schedules = schedules.filter(schedule => 
					(schedule.type || 'schedule') === state.filters.type
				)
			}
			
			// 按标签过滤
			if (state.filters.tags.length > 0) {
				schedules = schedules.filter(schedule => 
					state.filters.tags.some(tag => schedule.tags.includes(tag))
				)
			}
			
			// 按完成状态过滤
			if (state.filters.completed !== 'all') {
				const isCompleted = state.filters.completed === 'completed'
				schedules = schedules.filter(schedule => schedule.completed === isCompleted)
			}
			
			// 按搜索关键词过滤
			if (state.searchKeyword.trim()) {
				const keyword = state.searchKeyword.toLowerCase()
				schedules = schedules.filter(schedule => 
					schedule.title.toLowerCase().includes(keyword) ||
					schedule.description.toLowerCase().includes(keyword)
				)
			}
			
			// 排除隐藏的已完成事项（仅在主页显示时）
			schedules = schedules.filter(schedule => 
				!(schedule.completed && state.hiddenCompletedSchedules.includes(schedule.id))
			)
			
			return schedules
		},
		
		// 获取已完成事项（包括隐藏的）
		completedSchedules: (state, getters) => {
			return getters.sortedSchedules.filter(schedule => schedule.completed)
		},
		
		// 获取隐藏的已完成事项
		hiddenCompletedSchedules: (state, getters) => {
			return getters.sortedSchedules.filter(schedule => 
				schedule.completed && state.hiddenCompletedSchedules.includes(schedule.id)
			)
		},
		
		// 获取所有标签
		allTags: (state) => {
			const tags = new Set()
			state.schedules.forEach(schedule => {
				schedule.tags.forEach(tag => tags.add(tag))
			})
			return Array.from(tags)
		},
		
		// 统计数据
		statistics: (state, getters) => {
			const total = state.schedules.length
			const completed = state.schedules.filter(s => s.completed).length
			const urgent = state.schedules.filter(s => s.priority === 'urgent' && !s.completed).length
			const overdue = state.schedules.filter(s => {
				const now = new Date()
				const deadline = new Date(s.endTime)
				return deadline < now && !s.completed
			}).length
			
			return {
				total,
				completed,
				urgent,
				overdue,
				completionRate: total > 0 ? Math.round((completed / total) * 100) : 0
			}
		}
	},
	
	mutations: {
		// 设置日程列表
		SET_SCHEDULES(state, schedules) {
			state.schedules = schedules
		},
		
		// 添加日程
		ADD_SCHEDULE(state, schedule) {
			state.schedules.push({
				...schedule,
				id: Date.now() + Math.random().toString(36).substr(2, 9),
				createdAt: new Date().toISOString(),
				updatedAt: new Date().toISOString()
			})
		},
		
		// 更新日程
		UPDATE_SCHEDULE(state, { id, updates }) {
			const index = state.schedules.findIndex(s => s.id === id)
			if (index !== -1) {
				state.schedules[index] = {
					...state.schedules[index],
					...updates,
					updatedAt: new Date().toISOString()
				}
			}
		},
		
		// 删除日程
		DELETE_SCHEDULE(state, id) {
			state.schedules = state.schedules.filter(s => s.id !== id)
		},
		
		// 切换完成状态
		TOGGLE_COMPLETED(state, id) {
			const schedule = state.schedules.find(s => s.id === id)
			if (schedule) {
				schedule.completed = !schedule.completed
				schedule.updatedAt = new Date().toISOString()
			}
		},
		
		// 切换隐藏已完成事项
		TOGGLE_HIDDEN_SCHEDULE(state, id) {
			const index = state.hiddenCompletedSchedules.indexOf(id)
			if (index > -1) {
				state.hiddenCompletedSchedules.splice(index, 1)
			} else {
				state.hiddenCompletedSchedules.push(id)
			}
		},
		
		// 隐藏已完成事项
		HIDE_COMPLETED_SCHEDULE(state, id) {
			if (!state.hiddenCompletedSchedules.includes(id)) {
				state.hiddenCompletedSchedules.push(id)
			}
		},
		
		// 显示已完成事项
		SHOW_COMPLETED_SCHEDULE(state, id) {
			state.hiddenCompletedSchedules = state.hiddenCompletedSchedules.filter(hiddenId => hiddenId !== id)
		},
		
		// 设置过滤条件
		SET_FILTERS(state, filters) {
			state.filters = { ...state.filters, ...filters }
		},
		
		// 设置搜索关键词
		SET_SEARCH_KEYWORD(state, keyword) {
			state.searchKeyword = keyword
		}
	},
	
	actions: {
		// 加载本地数据
		async loadSchedules({ commit, state }) {
			try {
				const data = uni.getStorageSync('schedules')
				if (data) {
					commit('SET_SCHEDULES', JSON.parse(data))
					// 更新日程提醒
					await scheduleReminder.updateReminders(state.schedules)
				}
			} catch (error) {
				console.error('加载日程数据失败:', error)
			}
		},
		
		// 保存到本地
		async saveSchedules({ state }) {
			try {
				uni.setStorageSync('schedules', JSON.stringify(state.schedules))
				// 更新日程提醒
				await scheduleReminder.updateReminders(state.schedules)
			} catch (error) {
				console.error('保存日程数据失败:', error)
			}
		},
		
		// 添加日程
		async addSchedule({ commit, dispatch }, schedule) {
			commit('ADD_SCHEDULE', schedule)
			await dispatch('saveSchedules')
		},
		
		// 更新日程
		async updateSchedule({ commit, dispatch }, { id, updates }) {
			commit('UPDATE_SCHEDULE', { id, updates })
			await dispatch('saveSchedules')
		},
		
		// 删除日程
		async deleteSchedule({ commit, dispatch }, id) {
			commit('DELETE_SCHEDULE', id)
			await dispatch('saveSchedules')
		},
		
		// 切换完成状态
		async toggleCompleted({ commit, dispatch }, id) {
			commit('TOGGLE_COMPLETED', id)
			await dispatch('saveSchedules')
		},
		
		// 批量操作
		async batchDelete({ commit, dispatch }, ids) {
			ids.forEach(id => commit('DELETE_SCHEDULE', id))
			await dispatch('saveSchedules')
		},
		
		// 隐藏已完成事项
		async hideCompletedSchedule({ commit }, id) {
			commit('HIDE_COMPLETED_SCHEDULE', id)
		},
		
		// 显示已完成事项
		async showCompletedSchedule({ commit }, id) {
			commit('SHOW_COMPLETED_SCHEDULE', id)
		},
		
		// 批量隐藏已完成事项
		async batchHideCompletedSchedules({ commit }, ids) {
			ids.forEach(id => commit('HIDE_COMPLETED_SCHEDULE', id))
		},
		
		// 批量显示已完成事项
		async batchShowCompletedSchedules({ commit }, ids) {
			ids.forEach(id => commit('SHOW_COMPLETED_SCHEDULE', id))
		},
		
		// 初始化日程提醒服务
		async initReminderService({ state }) {
			try {
				await scheduleReminder.init()
				await scheduleReminder.updateReminders(state.schedules)
				console.log('日程提醒服务初始化完成')
			} catch (error) {
				console.error('初始化日程提醒服务失败:', error)
			}
		},
		
		// 清除所有日程提醒
		async clearAllReminders() {
			try {
				await scheduleReminder.clearAllReminders()
				console.log('已清除所有日程提醒')
			} catch (error) {
				console.error('清除日程提醒失败:', error)
			}
		}
	}
} 